﻿using System;
using System.Collections.Generic;
using System.Text;
using MVCFoto.IDAL;
using MVCFoto.Model;
using System.Web;

namespace MVCFoto.BLL
{
    public class Tag
    {
        private static readonly ITag dal = MVCFoto.DALFactory.Factory.Create<ITag>("Tag");
        public int AddTag(string name)
        {
            //存在则直接返回tagid
            TagInfo tag = dal.GetTag(name);
            if (tag != null)
                return tag.TagID;
            else
                return dal.AddTag(name);
        }

        public bool AddPhotoTag(int photoId, int tagId)
        {
            return dal.AddPhotoTag(photoId, tagId);
        }

        public bool DeletePhotoTag(int photoId, int tagId)
        {
            return dal.DeletePhotoTag(photoId, tagId);
        }
        public bool DeletePhotoTag(int photoId, string tagId)
        {
            TagInfo tag = dal.GetTag(tagId);
            if (tag != null)
                return DeletePhotoTag(photoId, tag.TagID);
            else
                return false;
        }
        public TagInfo GetTag(string name)
        {
            return dal.GetTag(name);
        }

        /// <summary>
        /// 为照片添加tag
        /// </summary>
        /// <param name="photoId"></param>
        /// <param name="tags">空格分格的tags</param>
        /// <returns></returns>
        public void AddPhotoTags(int photoId, string tags)
        {
            tags = tags.Replace("　", " ");
            string[] taglist = tags.Split(new char[] { ' ' });
            foreach (string t in taglist)
            {
                if (!String.IsNullOrEmpty(t))
                {
                    int tagId = AddTag(HttpUtility.HtmlEncode(t));
                    if (tagId > 0)
                    {
                       AddPhotoTag(photoId, tagId);
                    }
                }
            }
           
        }
        public IList<TagInfo> GetPhotoTags(int photoId)
        {

            return dal.GetPhotoTags(photoId);
        }

    }
}
